package pl.itconsus.dao.utils.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import pl.itconsus.dao.utils.BaseDao;
import pl.itconsus.model.entities.utils.BaseEntity;


@Transactional(propagation = Propagation.MANDATORY)
public class BaseDaoImpl<E extends BaseEntity<ID>, ID extends Serializable>
		extends HibernateDaoSupport implements BaseDao<E, ID> {

	private Class<E> persistentClass;

	public BaseDaoImpl(Class<E> persistentClass) {
		this.persistentClass = persistentClass;
	}

	/**
	 * Helper method for spring framework allowing injecting HibernateTemplate
	 * to all daos extending BaseServiceImpl (autoinject by name)
	 * 
	 * @param hibernateTemplate
	 *            spring definition for HibernateTemplate
	 */
	@Autowired
	public void setHT(HibernateTemplate hibernateTemplate) {
		super.setHibernateTemplate(hibernateTemplate);
	}

	public E get(ID id) {
		return getHibernateTemplate().get(persistentClass, id);
	}

	public void saveOrUpdate(E entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}

	@SuppressWarnings("unchecked")
	public List<E> list() {
		return getHibernateTemplate().findByCriteria(DetachedCriteria.forClass(persistentClass));
	}

	public E merge(E element) {
		return getHibernateTemplate().merge(element);
		
	};

}
